#!/usr/bin/python
# -*- coding: UTF-8 -*-

from pymongo import MongoClient
import anagraph
import json
import sys

reload(sys)
sys.setdefaultencoding('utf8')

class MongoData():
    def __init__(self, db_charset = 'utf8'):
        try:
            self.mongo_client = self.__connectMongo()
        except "InitMongoErr":
            print "connect mongo error, please check config file exists"

        self.insert_db = self.mongo_client['medicines']

        self.obj_ana = anagraph.Anagraph()

    def __del__(self):
        self.mongo_client.close()

    def __loadConfig(self):
        try:
            fp = open('./settings.json', 'r')
        except FileOperateError, e:
            print 'open config error'

        config = fp.read()
        config = json.loads(config)

        fp.close()

        return config

    def __connectMongo(self):
        self.config = self.__loadConfig()

        if self.config['mongo_uri']:
            mongo_client = MongoClient(self.config['mongo_uri'])

            return mongo_client
        else:
            raise Exception("InitMongoErr", "Init Mongo Client Error: missing config file")


    def flushData(self):
        collect_names = {
            'medicine_sh':'伤寒杂病论',
            'medicine_jk':'金匮要略',
            'medicine_zh':'肘后备急方',
            'medicine_bj':'备急千金要方',
            'medicine_qj':'千金翼方'
        }

        #flush all medicine data
        if 0 != len(self.insert_db.collection_names()):
            for (col_name, name) in collect_names.items():
                self.insert_db.drop_collection(col_name)

    def resetData(self):
        #remove all data and rewrite all
        self.flushData()
        self.__writeData()

    def __writeData(self):
        collect_names = {
            'medicine_sh':'伤寒杂病论',
            'medicine_jk':'金匮要略',
            'medicine_zh':'肘后备急方',
            'medicine_bj':'备急千金要方',
            'medicine_qj':'千金翼方'
        }

        for (col_name, ana_name) in collect_names.items():
            ana_list = self.obj_ana.getAnagraphs(ana_name)

            col = self.insert_db[col_name]

            if len(ana_list) != 0:
                for ana_item in ana_list:
                    if ana_item.has_key('name') and ana_item.has_key('medicines'):
                        col.insert_one(ana_item)
